<template>
   <div class="app-container">
        <!-- 相册信息 -->
        <el-row :gutter="12" class="mb15">
            <el-col :span="1.5">
                <el-image fit="cover" class="album-cover" :src="albumInfo.albumCover">
                </el-image>
            </el-col>
            <el-col :span="12">
                <el-row align="bottom">
                    <span class="album-name">{{ albumInfo.albumName }}</span>
                    <span class="photo-count">{{ albumInfo.photoCount }}张</span>
                </el-row>
                <el-row class="album-desc">{{ albumInfo.albumDesc }}</el-row>
                <el-row class="select-count">已选择{{ selectPhotoIdList.length }}张</el-row>
            </el-col>
        </el-row>
        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb20">
            <el-col :span="1.5">
                <el-button type="primary" plain class="el-icon-upload" @click="upload = true">上传</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="success" plain icon="Promotion"
                    :disabled="selectPhotoIdList.length == 0">移动</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="danger" plain class="el-icon-delete" :disabled="selectPhotoIdList.length == 0"
                    @click="handleDelete"> 批量删除</el-button>
            </el-col>
            <el-col style="margin-top:5px" :span="1.5">
                <el-checkbox   v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                    <div style="margin-left:24px;margin-top:2px">全选</div>
                </el-checkbox>
            </el-col>
        </el-row>
        <!-- 照片列表 -->
        <el-checkbox-group v-model="selectPhotoIdList" @change="handleCheckedPhotoChange">
            <el-row class="picture-list" :gutter="10">
                <el-col :xs="12" :sm="6" :lg="4" v-for="photo of photoList" :key="photo.id" style="margin-bottom:1rem;">
                    <el-checkbox  :label="photo.id">
                        <template #default>
                            <div class="photo-item">
                                <div class="photo-operation">
                                    <el-dropdown @command="handleCommand">
                                       <span class="el-dropdown-link" style="color:#fff">
                                            <i class="el-icon-arrow-down el-icon-more"></i>
                                        </span>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item :command="photo">编辑</el-dropdown-item>
                                                <el-dropdown-item :command="photo.id">删除</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                                <el-image class="photo-cover" fit="cover" :src="photo.photoUrl"
                                    :preview-src-list="[photo.photoUrl]">
                                </el-image>
                                <div class="photo-name">{{ photo.photoName }}</div>
                            </div>
                        </template>
                    </el-checkbox>
                </el-col>
            </el-row>
        </el-checkbox-group>
        <!-- 分页 -->
   <Pagination
      :total="count"   
      :page.sync="queryParams.current" 
      :limit.sync="queryParams.size"     
      @pagination="getAlbumInfo" 
    />
        <!-- 修改对话框 -->
        <el-dialog title="修改照片" :visible.sync="update" width="550px" append-to-body>
            <el-form ref="photoFormRef" label-width="100px" :model="photoForm" :rules="rules">
                <el-form-item label="照片名称" prop="photoName">
                    <el-input placeholder="请输入照片名称" v-model="photoForm.photoName" style="width: 250px;" />
                </el-form-item>
                <el-form-item label="照片描述" prop="photoDesc">
                    <el-input placeholder="请输入照片描述" v-model="photoForm.photoDesc" style="width: 250px;" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="update = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 上传对话框 -->
        <el-dialog title="上传照片"  :visible.sync="upload" width="800px" height="50px" append-to-body>
            <div class="">
                <el-upload v-show="uploadList.length > 0" :headers="authorization"  multiple
                    action="/api/admin/photo/upload" :before-upload="beforeUpload" :on-success="handleSuccess"   :data="{albumId:albumID}" 
                    :on-remove="handleRemove" :on-preview="handlePictureCardPreview" list-type="picture-card"    :on-progress="handleProgress"
                    :file-list="uploadList" accept="image/*">
                    <img class="avatar" />
                    <i class="el-icon-plus" ></i>
                </el-upload>
                   <el-progress v-if="progressFlag" :percentage="uploadPercentage"></el-progress>
                <div class="upload-container upload" v-show="uploadList.length === 0">
                  <div class="centered-upload">
                    <el-upload  :headers="authorization" drag multiple
                        action="/api/admin/photo/upload" :before-upload="beforeUpload" :show-file-list="false"    :on-progress="handleProgress"
                        :data="{albumId:albumID}" 
                        accept="image/*" :on-success="handleSuccess" style="width:360px;">
                         <i class="el-icon-upload"></i>
                        <div class="el-upload__text">
                            将文件拖到此处，或<em>点击上传</em>
                        </div>
                        <img width="360" />
                    </el-upload>
                  </div>
                 
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <div>
                        共上传{{ uploadList.length }}张照片
                    </div>
                    <div>
                        <el-button  type="primary" :disabled="uploadList.length == 0" @click="handleAdd">确 定</el-button>
                        <el-button @click="upload = false">取 消</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
        <!-- 图片预览 -->
        <el-dialog v-model="dialogVisible" append-to-body>
            <img :src="dialogImageUrl" style="max-width:100%" />
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth';
import {getPhotoInfo, addPhoto, getPhotoList, updatePhoto,deletePhoto } from '@/api/photo'
export default {
  data() {
    return {
      count: 0,
      loading: false,
      upload: false,
      update: false,
      checkAll: false,
      isIndeterminate: false,
      dialogImageUrl: "",
      dialogVisible: false,
      queryParams: {
          current: 1,
          size: 12,
          albumId: this.albumID,
      },
      photoForm: {},
      photoIdList: [],
      selectPhotoIdList: [],
      photoList: [],
      albumInfo: {},
      uploadList: [],
      rules:{ 
        photoName: [
          { required: true, message: "请输入照片名称", trigger: "blur" },
        ],
      },
      progressFlag: false, // 是否显示进度条
      uploadPercentage: 0, // 上传进度
    }  
  },
  methods: {
    getAlbumInfo(){
        this.loading = true;
      getPhotoInfo(this.$route.params.albumId).then(res => {
        if(res.code == 200){
          this.albumInfo = res.data
          this.loading = false;
        }
      })
      this.queryParams.albumId = this.albumID
      getPhotoList(this.queryParams).then(res => {
         this.loading = true;
        if(res.code == 200){
          this.photoList = res.data.recordList;
          this.count = res.data.count;
           this.loading = false;
        }
      })
    },
    handleDelete(){
        this.$confirm('此操作将永久删除该照片, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(
            () => {
                deletePhoto(this.selectPhotoIdList).then(res => {
                    if(res.code == 200){
                        this.$message({type:'success',message:'删除成功'})
                        this.getAlbumInfo()
                    }
                })
            }
        ).catch(() => {
            this.$message({
            type: 'info',
            message: '已取消删除'
            });          
        });
    },
    handleCheckAllChange(){
        this.isIndeterminate = false;
        if (this.checkAll) {
            this.selectPhotoIdList = this.photoList.map(item => item.id);
        } else {
            this.selectPhotoIdList = [];
        }
    },
    handleSizeChange(){},
    handleSuccess(response){
      this.uploadList.push({ url: response.data });
      this.uploadPercentage = 100;
      this.progressFlag = false;
    },
    handleRemove(){},
    handlePictureCardPreview(){},
    beforeUpload(file){
   // 获取文件大小，单位为字节
      const fileSize = file.size;
      // 允许的文件类型数组
      const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg'];
      // 文件类型不在允许的类型列表中
      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传jpg/png文件');
        return false; // 终止上传
      }
      let commonSize = 1024*1024*10;
      // 文件大小超过5MB
      if (fileSize > commonSize) {
        this.$message.error('文件大小不能超过5MB');
        return false; // 终止上传
      }
      return true; // 允许上传
    },
            //上传进度
    handleProgress(event, file, fileList) {
      this.progressFlag = true; // 显示进度条
      // 计算上传进度
      this.uploadPercentage = event.percent
      if(event.percent >= 99)
      {
        this.uploadPercentage = 99
      }
    },
    submitForm(){
        updatePhoto(this.photoForm).then(res => {
          if(res.code == 200){
            this.$message({type:'success',message:'修改成功'})
            this.update = false
            this.getAlbumInfo()
          }
        })
    },
    handleCheckedPhotoChange(){},
    handleCurrentChange(){},
    handleAdd(){
       // 假设你有一个名为 uploadList 的数组
        this.uploadList = this.uploadList.map(item => {
        // 使用解构赋值将原来的 url 属性重命名为 photoUrl
        const { url: photoUrl, ...rest } = item;
        return { photoUrl, albumId: this.albumID, ...rest };
        });
        addPhoto(this.uploadList).then(res => {
          if(res.code == 200){
            this.$message({type:'success',message:'上传成功'})
            this.upload = false
            this.uploadList = []
            this.getAlbumInfo()
          }
        });
    },
    handleCommand(command){
        if(command.id == undefined ){
            deletePhoto([command]).then(res => {
                if(res.code == 200){
                    this.$message({type:'success',message:'删除成功'})
                    this.getAlbumInfo()
                }
            });
        }else{
        this.update = true
        this.photoForm = command
        }
    },
  },
  computed:{
    albumID(){
      return this.$route.params.albumId
    },
    authorization() {
      const token = getToken()
      return {token}
    },

  },
  mounted(){
    this.getAlbumInfo();
  }
}
</script>

<style scoped>
.album-cover {
    border-radius: 4px;
    width: 5rem;
    height: 5rem;
}

.album-name {
    font-size: 1.25rem;
}

.photo-count {
    font-size: 13px;
    margin: 0 0 0.1rem 0.5rem;
}

.album-desc {
    font-size: 15px;
    margin-top: 0.4rem;
}

.select-count {
    font-size: 13px;
    margin-top: 0.4rem;
}

.checkbox .el-checkbox__input{
     position: absolute !important;
    white-space: nowrap;
    cursor: pointer;
    outline: none;
    display: inline-block;
    line-height: 1;
    position: relative;
    vertical-align: middle;
    margin-left: 14px;
    margin-top: 3px;
}

/* .el-checkbox__input{
    position: absolute !important;
    white-space: nowrap;
    cursor: pointer;
    outline: none;
    display: inline-block;
    line-height: 1;
    position: relative;
    vertical-align: middle;
    margin-left: 14px;
    margin-top: 3px;
} */

.el-checkbox >>> .el-checkbox__input {
    position: absolute !important;
    white-space: nowrap;
    cursor: pointer;
    outline: none;
    display: inline-block;
    line-height: 1;
    position: relative;
    vertical-align: middle;
    margin-left: 14px;
    margin-top: 3px;
}

.photo-item {
    position: relative;
    width: 100%;
    cursor: pointer;

    margin-bottom: 1rem;

    .photo-operation {
        position: absolute;
        top: 0.3rem;
        right: 0.5rem;
        z-index: 9;
    }

    .photo-cover {
        width: 100%;
        height: 7rem;
        border-radius: 4px;
    }

    .photo-name {
        font-size: 14px;
        margin-top: 0.3rem;
        text-align: center;
    }
}

.upload-container {
    height: 400px;

    .upload {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        width: 50%;
    }
}

.dialog-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.upload-container .el-upload {
    @import width: 100%;
}
.photo-name{
    height: 10px;
}

.centered-upload{
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100%; /* 设置高度以填充父容器 */
}
.picture-list{
    margin-top: 20px;
}


</style>